from rest_framework import serializers
from django.contrib.auth.hashers import check_password
from django.core.exceptions import ObjectDoesNotExist
from login.models import Users

class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField()  # 使用EmailField更专业
    password = serializers.CharField(
        write_only=True,
        style={'input_type': 'password'},  # 在DRF浏览API中显示为密码输入框
        trim_whitespace=False  # 不自动去除密码中的空格
    )
    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        if not email or not password:
            raise serializers.ValidationError("必须提供邮箱和密码")
        try:
            user = Users.objects.get(email=email,is_active=1)
        except ObjectDoesNotExist:
            raise serializers.ValidationError("用户不存在")
        if not check_password(password, user.password_hash):
            raise serializers.ValidationError("密码错误")
        return attrs
